package com.superatom.springframework.boot;

import com.superatom.springframework.util.ClassUtils;

/**
 * @author Kwokchiu Wong
 * @Title:
 * @Package
 * @Description:
 * @date 2020/10/16 3:27 下午
 */
public enum WebApplicationType {
    /**
     * 不作为web application启动，没有内置web server
     */
    NONE,

    /**
     * 内置Servlet web server
     */
    SERVLET,

    /**
     * 内置reactive web server
     */
    REACTIVE;

    private static final String[] SERVLET_INDICATOR_CLASSES = { "javax.servlet.Servlet",
            "org.springframework.web.context.ConfigurableWebApplicationContext" };

    private static final String WEBMVC_INDICATOR_CLASS = "org.springframework."
            + "web.servlet.DispatcherServlet";

    private static final String WEBFLUX_INDICATOR_CLASS = "org."
            + "springframework.web.reactive.DispatcherHandler";

    // Jersey是一个RESTFUL请求服务JAVA框架
    private static final String JERSEY_INDICATOR_CLASS = "org.glassfish.jersey.servlet.ServletContainer";


    static WebApplicationType deduceFromClasspath(){
        // 如果存在reactive分发类，认为是reactive web server
        if (ClassUtils.isPresent(WEBFLUX_INDICATOR_CLASS, null)
                && !ClassUtils.isPresent(WEBMVC_INDICATOR_CLASS, null)
                && !ClassUtils.isPresent(JERSEY_INDICATOR_CLASS, null)) {
            return WebApplicationType.REACTIVE;
        }

        // 不存在Servlet类，认为是非Web应用
        for (String className : SERVLET_INDICATOR_CLASSES) {
            if (!ClassUtils.isPresent(className, null)) {
                return WebApplicationType.NONE;
            }
        }
        return WebApplicationType.SERVLET;
    }
}
